// 显示loading
export const showLoading = (title='请稍后')=>{
	uni.showLoading({
		title,
		mask:true
	})
}

// 短提示
export const toast = (title, duration = 2000) => {
	uni.showToast({
		title,
		duration,
		icon: 'none'
	})
}

// 确认提示
export const modal = (content,showCancel=false) => {
	uni.showModal({
		title:'提示',
		content,
		showCancel
	})
}

// 复制文本
export const copyTxt = data => {
	if (!data) return toast('复制内容为空')
	uni.setClipboardData({
		data,
		success: () => {
			toast('复制成功')
		},
		fail: (err) => {
			toast('复制失败')
			console.log('复制失败err: ', err);
		}
	})
}

// 图片预览
export const previewImage = images => {
	uni.previewImage({
		urls: typeof images === 'string' ? [images] : images,
		current: 0
	})
}

// 生成随机数
export const random = (length=4)=>{
	let str = ''
	for(let i = 0; i<length; i++){
		str += Math.floor(Math.random()*10)
	}
	return str
}

// 文件另存为
export const downloadFile = (url,name=new Date()) => {
	const fileUrl = url; // 替换为你的文件URL
	const fileName = name; // 自定义保存文件名

	const a = document.createElement('a');
	a.href = fileUrl;
	a.download = fileName; // 设置下载文件名

	// 兼容性处理
	if (navigator.msSaveBlob) { // IE10+
		navigator.msSaveBlob(new Blob([a.href]), fileName);
	} else {
		document.body.appendChild(a);
		a.click();
		document.body.removeChild(a);
	}
}

// 时间过滤
import Moment2 from 'moment'
export const Moment = Moment2
export const moment = (date,type='YYYY-MM-DD HH:mm:ss')=>{
	if(!date) return '-'
	return Moment2(date).format(type)
}


// 检查更新
import { check } from '@tauri-apps/plugin-updater';
import { relaunch } from '@tauri-apps/plugin-process';
export const checkUpdate = async ()=>{
	const update = await check();
	console.log('update: ',update);
	if (update) {
		console.log(
		  `found update ${update.version} from ${update.date} with notes ${update.body}`
		);
		uni.showModal({
			title:`新版本 ${update.version}`,
			content:update.body || '检测到有新版本,请立即更新',
			showCancel:false,
			success: async() => {
				let downloaded = 0;
				let contentLength = 0;
				// alternatively we could also call update.download() and update.install() separately
				await update.downloadAndInstall((event) => {
				  switch (event.event) {
				    case 'Started':
				      contentLength = event.data.contentLength;
				      console.log(`started downloading ${event.data.contentLength} bytes`);
				      break;
				    case 'Progress':
				      downloaded += event.data.chunkLength;
				      console.log(`downloaded ${downloaded} from ${contentLength}`);
				      break;
				    case 'Finished':
				      console.log('download finished');
				      break;
				  }
				});
					
				console.log('update installed');
				await relaunch();
			}
		})
	  
	}
}